<?php

namespace api\modules\v1\models;

use api\func\func;
use Yii;
use api\common\models\Common;
use api\common\models\Mar;
use yii\base\Exception;
use yii\web\NotFoundHttpException;
use yii\web\HttpException;
use api\modules\v1\models\News;
use api\modules\v1\models\Msg;
use api\modules\v1\models\Comment;
use yii\db\Expression;
use yii\web\Request;
use yii\helpers\Url;
use yii\data\Pagination;
class Like extends Common
{
    public static $_tableName = '{{%like_app}}' ;

    public static function tableName()
    {
        //return '{{%like_app}}';
        return self::$_tableName;
    }


    /*
     * 内容点赞
     * @param $id 内容id
     * @param $type 文章类型 1:新闻 2:视频
     */
    public function likeContent($content_id,$catid){
        $content_id = (int)$content_id;
        $catid = (int)$catid;
        $news_table = '{{%'.News::getTable($catid).'}}';
        self::$_tableName = self::tableExists(self::formatTable($content_id,Yii::$app->params['table_like']['num'],Yii::$app->params['table_like']['table']));
        $news = new Mar($news_table);
         if(!$news->findOnex($news_table,['id'=>$content_id])) {
            throw new NotFoundHttpException('该id的信息不存在.');
        }
        $user = $this->getTokenUserId();
        if($user !='' && is_array($user)) {
            if($this->findOne(['content_id'=>$content_id,'position_type'=>1,'catid'=>$catid,'uid'=>$user['id']])){
                throw new HttpException(401,'您已经赞过',0);
            }else {
                $news->updateAll(['like' => new Expression('`like` + 1')], ['id' => $content_id]);
                $this->uid = $user['id'];
                $this->username = $user['nickname'] != '' ? $user['nickname'] : $user['phone'];
                $this->time = date('Y-m-d H:i:s');
                $this->content_id = $content_id;
                $this->comment_id = 0;
                $this->position_type = 1; //赞位置 1:主文章赞 2:评论赞
                $this->catid = $catid; // 分类id
                $this->insert();
                //return true;
            }
        }else{
            $news->updateAll(['like' => new Expression('`like` + 1')], ['id' => $content_id]);
            //return true;
        }

        /*推荐位文章 点赞数据处理*/
        if($p_data = Recommend::find(['id'=>$content_id,'catid'=>$catid,'posid'=>1])->asArray()->one()){
            Recommend::updateAll(['like' => new Expression('`like` + 1')],['id'=>$content_id,'catid'=>$catid,'posid'=>1]);
        }
        /*推荐位文章 点赞数据处理*/
        return true;

    }


    /*
     * 内容点赞撤销
     * @param $id 内容id
     * @param $type 文章类型 1:新闻 2:视频
     */
    public function likeContentreset($content_id,$catid){
        $content_id = (int)$content_id;
        $catid = (int)$catid;
        $news_table = '{{%'.News::getTable($catid).'}}';
        self::$_tableName = self::tableExists(self::formatTable($content_id,Yii::$app->params['table_like']['num'],Yii::$app->params['table_like']['table']));
        $news = new Mar($news_table);
        if(!$data = $news->findOnex($news_table,['id'=>$content_id])) {
            throw new NotFoundHttpException('该id的信息不存在.');
        }

        $user = $this->getTokenUserId();
        if($user !='' && is_array($user)) {
            $this->deleteAll(['content_id'=>$content_id,'position_type'=>1,'catid'=>$catid,'uid'=>$user['id']]); //删除 like表点赞记录
            if($data->like >= 1) {
                $news->updateAll(['like' => new Expression('`like` - 1')], ['id' => $content_id]); //文章信息表 点赞数量 -1

                /*推荐位文章 点赞数据处理*/
                if($p_data = Recommend::find(['id'=>$content_id,'catid'=>$catid,'posid'=>1])->asArray()->one()){
                    if($p_data['like'] >= 1){
                        Recommend::updateAll(['like' => new Expression('`like` - 1')],['id'=>$content_id,'catid'=>$catid,'posid'=>1]);
                    }
                }
                /*推荐位文章 点赞数据处理*/
            }
            return true;
        }else{
            throw new HttpException(401,'未登录',0);
        }
    }

    /*
     * 评论点赞接口
     * @param $id
     * @param $catid
     * @return bool
     * @throws HttpException
     * @throws NotFoundHttpException
     * @throws \Exception
     */
    public function likeComment($content_id,$catid,$comment_id){
        $content_id = (int)$content_id;
        $catid = (int)$catid;
        $comment_id = (int)$comment_id;
        if(!$Comment = Comment::findOne([['comment_id'=>$comment_id]])){
            throw new NotFoundHttpException('该id的评论不存在.');
        }

        self::$_tableName = self::tableExists(self::formatTable($content_id,Yii::$app->params['table_like']['num'],Yii::$app->params['table_like']['table']));

        $user = $this->getTokenUserId();
        if($user !='' && is_array($user)){
            if($this->findOne(['comment_id'=>$comment_id,'content_id'=>$content_id,'position_type'=>2,'catid'=>$catid,'uid'=>$user['id']])){
                throw new HttpException(401,'您已经赞过',0);
            }else{
                Comment::updateAll(['like'=>new Expression('`like` + 1')],['comment_id'=>$comment_id]);//增加点赞数量
                $this->uid = $user['id'];
                $this->username = $user['nickname'] != '' ? $user['nickname'] : $user['phone'];
                $this->time = date('Y-m-d H:i:s');
                $this->content_id = $content_id;
                $this->comment_id = $comment_id;
                $this->position_type = 2; //赞位置 1:主文章赞 2:评论赞
                $this->catid = $catid; // 分类id
                $this->insert();

                $msg = new Msg();
                $msg->take_uid = $Comment['uid'];
                $msg->send_uid = $user['id'];
                $msg->message = $user['nickname'] != '' ? $user['nickname'] : $user['phone'].'对您的评论进行了点赞';
                $msg->type = 1;
                //$msg->url = Url::to(['comment/one', 'comment_id' => $comment_id], false);
                $msg->url = Url::to(['comment/list','content_id' => $this->content_id,'catid' => $this->catid,'pid' => $comment_id], false);
                $msg->time = date('Y-m-d H:i:s');
                $msg->isread = 0;
                $msg->insert();

                return true;
            }
        }else{
            Comment::updateAll(['like'=>new Expression('`like` + 1')],['comment_id'=>$comment_id]);
            return true;
        }
    }


    /*
     * 评论点赞撤销接口
     * @param $id
     * @param $catid
     * @return bool
     * @throws HttpException
     * @throws NotFoundHttpException
     * @throws \Exception
     */
    public function likeCommentreset($content_id,$catid,$comment_id){
        $content_id = (int)$content_id;
        $catid = (int)$catid;
        $comment_id = (int)$comment_id;
        if(!$Comment = Comment::findOne([['comment_id'=>$comment_id]])){
            throw new NotFoundHttpException('该id的评论不存在.');
        }

        self::$_tableName = self::tableExists(self::formatTable($content_id,Yii::$app->params['table_like']['num'],Yii::$app->params['table_like']['table']));

        $user = $this->getTokenUserId();
        if($user !='' && is_array($user)){
            $this->deleteAll(['comment_id'=>$comment_id,'content_id'=>$content_id,'position_type'=>2,'catid'=>$catid,'uid'=>$user['id']]); //删除 like表点赞记录
            if($Comment->like >= 1){
                Comment::updateAll(['like'=>new Expression('`like` - 1')],['comment_id'=>$comment_id]);//评论表点赞数量-1
            }
            $msg = new Msg();
            $msg->deleteAll(['take_uid'=>$Comment['uid'],'send_uid'=>$user['id'],'type'=>1,'url'=>Url::to(['comment/list','content_id' => $content_id,'catid' => $catid,'pid' => $comment_id], false)]); //删除消息通知
            return true;
        }else{
            throw new HttpException(401,'未登录',0);
        }
    }

    /*
     * 点赞文章列表
     * @param $content_id
     * @param $catid
     */
    public function Contentlist($content_id,$catid){
        $content_id = (int)$content_id;
        $catid = (int)$catid;
        self::$_tableName = self::tableExists(self::formatTable($content_id,Yii::$app->params['table_like']['num'],Yii::$app->params['table_like']['table']));
        $query = (new \yii\db\Query());
        $query->from(self::$_tableName.' as a');
        $query->leftJoin('{{%user_app}} as b','a.uid = b.id');
        $query->select('a.*,b.head_img,b.username,b.nickname,b.phone');
        $query->where(['content_id'=>$content_id,'position_type'=>1,'catid'=>$catid]);
        $count = $query->count();

        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->defaultPageSize = Yii::$app->params['page_size'];
        $data = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->orderBy('a.time asc')
            ->all();
        $this->serializePagination($pagination);
        $pagination->defaultPageSize = Yii::$app->params['page_size'];

        $ImgBaseUrl = self::getImgBaseUrl();
        foreach($data as $k=>$v){
            $data[$k]['phone'] = $v['phone'] != '' ? func::replace_phone($v['phone']) : $v['phone'];
        }

        $_data = [];
        $_data['items'] = $data;
        $_data['_links'] = $this->linksEnvelope;
        $_data['_meta'] = $this->metaEnvelope;
        return $_data;
    }

    /*
     * 点赞评论列表
     * @param $content_id
     * @param $catid
     */
    public function Commentlist($content_id,$comment_id,$catid){
        $content_id = (int)$content_id;
        $catid = (int)$catid;
        $comment_id = (int)$comment_id;
        self::$_tableName = self::tableExists(self::formatTable($content_id,Yii::$app->params['table_like']['num'],Yii::$app->params['table_like']['table']));
        $query = (new \yii\db\Query());
        $query->from(self::$_tableName.' as a');
        $query->leftJoin('{{%user_app}} as b','a.uid = b.id');
        $query->select('a.*,b.head_img,b.username,b.nickname,b.phone');
        $query->where(['comment_id'=>$comment_id,'content_id'=>$content_id,'position_type'=>2,'catid'=>$catid]);
        $count = $query->count();

        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->defaultPageSize = Yii::$app->params['page_size'];

        $data = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->orderBy('a.time asc')
            ->all();
        $this->serializePagination($pagination);
        $pagination->defaultPageSize = Yii::$app->params['page_size'];

/*        $ImgBaseUrl = self::getImgBaseUrl();
        foreach($data as $k=>$v){
            if($v['head_img'] !=''){
                $data[$k]['head_img'] = $ImgBaseUrl.substr($v['head_img'],1);
            }
        }*/

        foreach($data as $k=>$v){
            $data[$k]['phone'] = $v['phone'] != '' ? func::replace_phone($v['phone']) : $v['phone'];
        }

        $_data = [];
        $_data['items'] = $data;
        $_data['_links'] = $this->linksEnvelope;
        $_data['_meta'] = $this->metaEnvelope;
        return $_data;
    }

    /*
     * 统计系统推送
     * @param int $is_canel
     * @throws NotFoundHttpException
     */
    public function PushTj($content_id,$catid,$is_canel=1){
        try{
            $news_data = News::getInfoSim($content_id,$catid);
            if($news_data['thirdid'] =='' || $news_data['thirdid'] == 0) return true;
            $user = func::IdToUser($news_data['thirdid']);
            $nickname = $user->nickname != '' ? $user->nickname :func::replace_phone($user->phone);
            $phone = $user->phone;
            $data = '{"User_id":'.Yii::$app->user->identity->id.',"is_cancel":'.$is_canel.',"Article_id":'.$content_id.',"Article_type":'.$catid.',"Fabulous_time":"'.date('Y-m-d H:i:s').'","Article_title":"'.$news_data['title'].'","Nickname":"'.$nickname.'","Phone":'.$phone.'}';
            $data = array('data' => $data,'key'=>'c3RhdGlzdGlj');
            $json = func::GoCurl('/api/fabulous/insert',  'POST',$data, $error_msg);
            $array = json_decode($json, true);
            if($array['Code'] != 10000){

            }
        }catch (Exception $e){}
    }




    /*
 * 查找表是否存在 不存在则创建
 * @param $table
 */
    public static function tableExists($tableName){
        $db = \Yii::$app->db;
        if($db->createCommand("SHOW TABLES LIKE '".$tableName."'")->queryAll()==null)
        {
            $sql = <<<EOT
CREATE TABLE $tableName (
  `like_id` int(11) NOT NULL AUTO_INCREMENT,
  `uid` int(11) NOT NULL COMMENT '用户id',
  `username` varchar(50) NOT NULL COMMENT '用户名',
  `time` datetime NOT NULL COMMENT '时间',
  `content_id` int(11) NOT NULL COMMENT '文章id',
  `comment_id` int(11) NOT NULL DEFAULT '0' COMMENT '留言id',
  `position_type` tinyint(1) NOT NULL COMMENT '赞位置 1:主文章赞 2:评论赞',
  `catid` int(11) NOT NULL COMMENT '分类id',
  PRIMARY KEY (`like_id`),
  KEY `catid` (`catid`),
  KEY `content_id` (`content_id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='点赞接口表';

EOT;
            ;
            $db->createCommand($sql)->execute();
        }

        return $tableName;
    }
}
